package com.m4f.cityclient.common.service.impl;

import java.util.ArrayList;
import java.util.logging.Logger;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.m4f.cityclient.common.model.M4FOAuthUser;
import com.m4f.cityclient.common.service.ifc.M4FOAuthUserService;
import com.m4f.gaeweb.business.service.impl.GaeM4FUserDetailService;
import com.m4f.gaeweb.model.GaeM4FUser;

public class InternalUserDetailService extends GaeM4FUserDetailService {
	
	private static final Logger LOGGER = Logger.getLogger(InternalUserDetailService.class.getName());
	
	private M4FOAuthUserService userService;
	
	public InternalUserDetailService(String rootUser, String rootPassword) {
		super(rootUser, rootPassword);
	}

	@Override
	public GaeM4FUser loadGaeM4FUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		try {
			M4FOAuthUser user = this.userService.getUser(username);
			if(user != null) {
				ArrayList<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
				user.setAuthorities(authorities);
			} else {
				throw new UsernameNotFoundException("User not found: " + username);
			}
			return user;
		} catch(Exception e) {
			throw new UsernameNotFoundException("User not found: " + username);
		}
	}

	@Override
	public GaeM4FUser createRootUser() {
		M4FOAuthUser root = userService.createUser();
		root.setEmail(this.rootUserName);
		root.setPassword(this.rootEncodedPassword);
		
		return root;
	}

	public void setUserService(M4FOAuthUserService userService) {
		this.userService = userService;
	}
}